﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Drawing;

namespace Networking
{
    public class Client
    {
        TcpClient client;
        IPAddress ipAddress;
        int port;

        bool IsListening;
        Thread listenThread;
        NetworkStream stream;
        BinaryReader reader;
        BinaryWriter writer;

        IScreenManager screenManager;

        public Client(string IP, int port, IScreenManager screenManager)
        {
            ipAddress = IPAddress.Parse(IP);
            this.port = port;

            client = new TcpClient();
            this.screenManager = screenManager;
        }

        public void Connect()
        {
            client.Connect(ipAddress, port);
            Console.WriteLine("Client is " + (client.Connected ? " " : "NOT ") + "connected");

            if (client.Connected)
            {
                stream = client.GetStream();

                listenThread = new Thread(new ThreadStart(Start));
                listenThread.Start();
            }
        }

        protected void Start()
        {
            IsListening = true;
            reader = new BinaryReader(stream);
            writer = new BinaryWriter(stream);
            BinaryFormatter formatter = new BinaryFormatter();

            while (IsListening)
            {
                try
                {
                    Bitmap bitmap = screenManager.TakeScreenShot();
                    if (bitmap != null)
                    {
                        formatter.Serialize(stream, bitmap);
                    }
                }
                catch (Exception)
                {
                }
            }
        }
    }
}
